package com.example.easypoi.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.easypoi.dao.UserMapper;
import com.example.easypoi.entity.RespBean;
import com.example.easypoi.entity.User;
import com.example.easypoi.service.IUserService;
import com.example.easypoi.util.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public RespBean importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        List<User> list = ExcelUtils.importExcel(file, User.class);
        boolean batch = userService.saveOrUpdateBatch(list);
        if (batch) {
            return RespBean.ok("导入成功");
        } else {
            return RespBean.error("导入失败");
        }
    }

    /**
     * 导出数据，使用map接收
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/exportExcel")
    public void exportExcel(String name, HttpServletResponse response) throws IOException {
        IPage<User> iPage = userService.getList(name, 1, 10);
        ExcelUtils.exportExcel(iPage.getRecords(), "ex", "test", User.class, "ee", response);
    }
}
